package com.lang8.util.database;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionUtil {
	private static ConnectionUtil instance = null;
	private BasicDataSource dataSource = null;
	private ConnectionUtil(){}
	public static ConnectionUtil getInstance(){
		if(instance == null){
			synchronized (ConnectionUtil.class) {
				if (instance == null) {
					instance = new ConnectionUtil();
					instance.initInstance();
				}
			}
		}
		return instance;
	}
	private void initInstance() {
		try {
			Properties p = new Properties();
			p.load(ConnectionUtil.class.getResourceAsStream("/com/lang8/config/jdbc.properties"));
			dataSource = new BasicDataSource();
			dataSource.setDriverClassName(p.getProperty("jdbc.driverClassName"));
			dataSource.setUsername(p.getProperty("jdbc.username"));
			dataSource.setPassword(p.getProperty("jdbc.password"));
			dataSource.setUrl(p.getProperty("jdbc.url"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		try {
			return getInstance().dataSource.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	public static void releaseConnection(ResultSet rs, Statement stmt, Connection conn){
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.setAutoCommit(true);
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	public static void rollback(Connection conn) {
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
	}
}
